package com.sunshine.annotation;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Method;

/**
 * 1.本例子中，通过运行时反射获取注解内容    <br />
 * 2.也可以通过，拦截器获取运行时的注解 handler.getClass().getAnnotation(TestAnnotation.class)
 *
 * @author WeiHong
 * @date 2019/8/5 16:51
 */
public class TestApp {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {

        Class<?> stuClass = Class.forName("com.sunshine.annotation.Student");

        //类的注解获取
        if (stuClass.isAnnotationPresent(TestAnnotation.class)) {
            TestAnnotation annotation = stuClass.getAnnotation(TestAnnotation.class);
            printAnnotation(annotation);
        }else {
            System.out.println("类上没有添加 @TestAnnotation 注解");
        }
        //方法的注解获取
        Method studentMethod = stuClass.getMethod("studentMethod");
        //是否加了@TestAnnotation注解
        if (studentMethod.isAnnotationPresent(TestAnnotation.class)) {
            TestAnnotation annotation = studentMethod.getAnnotation(TestAnnotation.class);
            printAnnotation(annotation);
        }else {
            System.out.println("方法上没有添加 @TestAnnotation 注解");
        }
    }

    /**
     * 打印注解内容
     *
     * @param annotation
     */
    public static void printAnnotation(TestAnnotation annotation) {
        System.out.println("name = " + annotation.name());
        System.out.println("age = " + annotation.age());
        int[] score = annotation.score();
        System.out.println("score = " + JSONObject.toJSONString(score));
        System.out.println("---------------------------");
    }
}
